package com.zdkj.subway.support.controller;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.support.entity.SwPmTvmCode;
import com.zdkj.subway.support.service.SwParamLineService;
import com.zdkj.subway.support.service.SwParamStationService;
import com.zdkj.subway.support.service.SwPmTvmCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * TVM编号参数表
 *
 * @author cuilei
 * @date 2020-05-28 14:03:49
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swpmtvmcode")
@Api(value = "swpmtvmcode", tags = "TVM编号参数表管理")
public class SwPmTvmCodeController {

	private static final Logger LOGGER = LoggerFactory.getLogger(SwPmTvmCodeController.class);

    private final SwPmTvmCodeService swPmTvmCodeService;
    
	private final SwParamLineService swPmLineService;

	private final SwParamStationService swPmStationService;

    /**
     * 分页查询
     *
     * @param page        分页对象
     * @param swPmTvmCode TVM编号参数表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwPmTvmCodePage(Page page, SwPmTvmCode swPmTvmCode) {
        if (!SecurityUtils.getUser().getBelongToLine()) {
            QueryWrapper<SwPmTvmCode> queryWrapper = Wrappers.query(swPmTvmCode);
            queryWrapper.lambda().eq(SwPmTvmCode::getLineCode, SecurityUtils.getUser().getLineCode());
            queryWrapper.lambda().eq(SwPmTvmCode::getStationCode, SecurityUtils.getUser().getStationCode());
            queryWrapper.orderByAsc("TVM_CODE");
            return R.ok(swPmTvmCodeService.page(page,queryWrapper ));
            /*return R.ok(swPmTvmCodeService.page(page, Wrappers.query(swPmTvmCode)
                    .lambda().eq(SwPmTvmCode::getStationCode, SecurityUtils.getUser().getStationCode())));*/
        }
        return R.ok(swPmTvmCodeService.page(page, Wrappers.query(swPmTvmCode)));
    }

    /**
     * 通过id查询TVM编号参数表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swPmTvmCodeService.getById(id));
    }

    /**
     * 新增TVM编号参数表
     *
     * @param swPmTvmCode TVM编号参数表
     * @return R
     */
    @ApiOperation(value = "新增TVM编号参数表", notes = "新增TVM编号参数表")
    //@SysLog("新增TVM编号参数表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('support_sw_pm_tvm_code_add')")
    public R save(@RequestBody SwPmTvmCode swPmTvmCode) {
        QueryWrapper<SwPmTvmCode> codequeryWrapper=new QueryWrapper<>();
        codequeryWrapper.eq("line_code",swPmTvmCode.getLineCode());
        codequeryWrapper.eq("station_code",swPmTvmCode.getStationCode());
        codequeryWrapper.eq("tvm_code",swPmTvmCode.getTvmCode());
        SwPmTvmCode codeswPmTvmCode=swPmTvmCodeService.getOne(codequeryWrapper);
        if(ObjectUtil.isNotEmpty(codeswPmTvmCode)){
            return R.failed(codeswPmTvmCode,swPmTvmCode.getLineCode()+"号线该车站TVM编号为"+codeswPmTvmCode.getTvmCode()+"的数据已存在,相同线路车站TVM编号不允许重复");
        }
        SwPmTvmCode defaultObj = ObjectUtils.getDefaultObj(SwPmTvmCode.class);
        BeanUtils.copyProperties(swPmTvmCode, defaultObj,
                ObjectUtils.getNullAndEmptyPropertyNames(swPmTvmCode));
        defaultObj.setLineCode(swPmTvmCode.getLineCode());
        defaultObj.setStationCode(swPmTvmCode.getStationCode());
        return R.ok(swPmTvmCodeService.save(defaultObj));
    }

    /**
     * 修改TVM编号参数表
     *
     * @param swPmTvmCode TVM编号参数表
     * @return R
     */
    @ApiOperation(value = "修改TVM编号参数表", notes = "修改TVM编号参数表")
    //@SysLog("修改TVM编号参数表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('support_sw_pm_tvm_code_edit')")
    public R updateById(@RequestBody SwPmTvmCode swPmTvmCode) {
        QueryWrapper<SwPmTvmCode> codequeryWrapper=new QueryWrapper<>();
        codequeryWrapper.eq("line_code",swPmTvmCode.getLineCode());
        codequeryWrapper.eq("station_code",swPmTvmCode.getStationCode());
        codequeryWrapper.eq("tvm_code",swPmTvmCode.getTvmCode());
        SwPmTvmCode codeswPmTvmCode=swPmTvmCodeService.getOne(codequeryWrapper);
        if(ObjectUtil.isNotEmpty(codeswPmTvmCode)&& !Objects.equals(swPmTvmCode.getId(),codeswPmTvmCode.getId())){
            return R.failed(codeswPmTvmCode,swPmTvmCode.getLineCode()+"号线该车站TVM编号为"+codeswPmTvmCode.getTvmCode()+"的数据已存在,相同线路车站TVM编号不允许重复");
        }
        return R.ok(swPmTvmCodeService.updateById(swPmTvmCode));
    }

    /**
     * 通过id删除TVM编号参数表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除TVM编号参数表", notes = "通过id删除TVM编号参数表")
    //@SysLog("通过id删除TVM编号参数表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('support_sw_pm_tvm_code_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swPmTvmCodeService.removeById(id));
    }

    /**
     * 导入TVM编号参数
     *
     * @param file
     * @return
     */
    /*
	@ApiOperation(value = "导入TVM编号参数", notes = "导入TVM编号参数")
    @SysLog("导入TVM编号参数")
    @PostMapping("/import")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), SwPmTvmCode.class,
                    new UploadDataListener(swPmTvmCodeService, SwPmTvmCode.class)).sheet().doRead();
            return R.ok("导入成功");
        } catch (IOException e) {
            log.info(e.getMessage());
            return R.ok("导入失败");
        }
    }
	*/

	/**
     * 导入TVM编号参数
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "导入TVM编号参数", notes = "导入TVM编号参数")
    //@SysLog("导入TVM编号参数")
    @PostMapping("/import")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        try {
            PigxUser pigxUser = SecurityUtils.getUser();          
		   final File excelFile = MultipartFileToFile.multipartFileToFile(file);
		   List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(1).doReadSync();
		   if (CollectionUtil.isNotEmpty(listMap)) {
			 MultipartFileToFile.delteTempFile(excelFile);
			for (int m = 0; m < listMap.size(); m++) {
				Map<Integer, String> data = listMap.get(m);
				// 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
				LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

				SwPmTvmCode tvmDto = new SwPmTvmCode();

				if(StringUtils.isNotEmpty(data.get(0).trim())){
					String lineCode = getLineCode(data.get(0).trim());
					if(StringUtils.isEmpty(lineCode)){
					  continue;
					}
					String stationCode = getStationCode(lineCode,data.get(1).trim()); 
					if(StringUtils.isEmpty(stationCode)){
					  continue;
					}
					String tvmCode = data.get(2).trim();
					if(StringUtils.isEmpty(tvmCode)){
					  continue;
					}


					//根据线路站点和TVM编号判断是否存在

					QueryWrapper<SwPmTvmCode> queryWrapper=new QueryWrapper<>();
					queryWrapper.eq("line_code",lineCode);
					queryWrapper.eq("station_code",stationCode);				
					queryWrapper.ge("tvm_code",tvmCode);
					queryWrapper.ge("del_flag","0");
					
					List<SwPmTvmCode> list = swPmTvmCodeService.list(queryWrapper);
					/*SwPmTvmCode pmTvmCode = swPmTvmCodeService.getOne(Wrappers.<SwPmTvmCode>lambdaQuery()
							.eq(SwPmTvmCode::getLineCode,lineCode)
						    .eq(SwPmTvmCode::getStationCode,stationCode)
					        .eq(SwPmTvmCode::getTvmCode, tvmCode));						    
							//.eq(SwPmTvmCode::getDelFlag,"0"));	*/						
					//不存在添加
					if(list==null || list.size()==0){
						tvmDto.setLineCode(lineCode);
						tvmDto.setStationCode(stationCode);
						tvmDto.setTvmCode(tvmCode);
						tvmDto.setStatus("1");
						tvmDto.setDelFlag("0");
						tvmDto.setDeptId(pigxUser.getDeptId());
						tvmDto.setCreatorId(pigxUser.getId());
                        tvmDto.setCreatorName(pigxUser.getNikeName());
                        tvmDto.setCreateTime(LocalDateTime.now()); 
						swPmTvmCodeService.save(tvmDto);
					}else {//存在修改
					    //SwPmTvmCode pmTvmCode = list.get(0);
						//pmTvmCode.setDelFlag("0");                        
						//swPmTvmCodeService.update(pmTvmCode);

					}
				}

			}
		}
		 return R.ok("导入成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            return R.ok("导入失败");
        }
    }

	/**
	 * 下载模板
	 * @param
	 * @return
	 * @throws
	 */
	@ApiOperation(value = "下载模板", notes = "下载模板")
	@GetMapping("/exportTamplate")
	public void exportTamplateKY(HttpServletResponse response) {
		String  verifyConfirmName = "TVM编号模板";
		String  tableName = "sw_pm_tvm_code";

		BufferedInputStream br = null;
		OutputStream out = null;
		try {
			response.reset(); // 非常重要
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			final String fileName = URLEncoder.encode(verifyConfirmName, "UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xls");

			br =  new BufferedInputStream(this.getClass().getResourceAsStream("/static/excel/template/import/" + tableName + ".xls"));

			byte[] buf = new byte[1024];
			int len = 0;

			out = response.getOutputStream();
			while ((len = br.read(buf)) > 0) {
				out.write(buf, 0, len);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(out != null) {
				try {
					out.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
			if(br != null){
				try {
					br.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		}
	}

    //查询线路
	private  String getLineCode(String lineName) {
		if(StringUtils.isNotEmpty(lineName)){
			return swPmLineService.getCodeByName(lineName);
		}
		return "";
	}
	 //查询车站编号
	private  String getStationCode(String lineCode,String stationName) {
		if(StringUtils.isNotEmpty(stationName)){
			return swPmStationService.getCodeByNameAndLineCode(stationName,lineCode);
		}
		return "";
	}


}
